import AuthApiService from "@/api/auth";
import { LS } from "@/utils/common";

// 初始值
const initialState = {
  adminname: '',
  checkedKeys: [],
  role: -1,
  token: ''
}
const auth = {
  namespaced: true,
  // state: () => ({
  //   adminname: '',
  //   checkedKeys: [],
  //   role: -1,
  //   token: ''
  // }),
  // 进入项目后,先从本地存储中获取数据,如果获取不到,就设置默认值
  state: () => LS.get('admininfo', initialState),
  getters: {
    // 判断是否登录
    isLoginined(state) {
      return !!state.adminname
    }
  },
  mutations: {
    // 更新用户信息
    updateAll(state, payload) {
      const { adminname, checkedKeys, role, token } = payload
      state.adminname = adminname
      state.checkedKeys = checkedKeys
      state.role = role
      state.token = token
      // 每次更新用户信息后,都要把最新的用户信息存储到本地
      LS.set('admininfo', payload)
    },
    // 退出登录
    logout(state) {
      for (let key in initialState) {
        state[key] = initialState[key]
      }
    }
  },
  actions: {
    // 登录
    async LoginAction({ commit }, payload) {
      try {
        const res = await AuthApiService.postLoginApi(payload.params);
        commit({ type: 'updateAll', ...res })
        return true // 用来标识登录成功
      } catch (error) {
        console.log(error, '---error')
      }
    },
    // 同步操作本地存储  退出登录
    logoutAction({ commit }) {
      LS.remove('admininfo')
      commit({ type: "resetAll" })
    }
  }
}
export default auth